<template>
  <view id="chatPage">
    <scroll-view scroll-y scroll-into-view="{{toView}}" style="height:{{scrollHeight}}" id="scrollView">
      <block v-for="(item, index) in msgList" :key="index">
        <!-- 客服消息（左侧） -->
        <view v-if="item.speaker==='server'" :id="'msg-' + index"
          style="display:flex; padding:2vw 11vw 2vw 2vw;">
          <view style="width:11vw;height:11vw;">
            <image style="width:11vw; height:11vw; border-radius:10rpx;" src="../../pic/机器人.png"></image>
          </view>
          <view style="width:4vw;height:11vw;margin-left:0.5vw;display:flex;align-items:center;z-index:9;">
            <image style="width:4vw;" src="../../pic/向左.png" mode="widthFix"></image>
          </view>
          <text user-select="{{true}}" class="leftMsg" space="nbsp" decode="{{true}}">
            {{item.content}}
          </text>
        </view>

        <!-- 用户消息（右侧） -->
        <view v-else :id="'msg-' + index"
          style="display:flex;justify-content:flex-end;padding:2vw 2vw 2vw 11vw;">
          <view class="rightMsg">{{item.content}}</view>
          <view style="width:4vw;height:11vw;margin-right:0.5vw;display:flex;align-items:center;z-index:9;">
            <image style="width:4vw;" src="../../pic/向右.png" mode="widthFix"></image>
          </view>
          <view style="width:11vw;height:11vw;">
            <image style="width:11vw;height:11vw;border-radius:10rpx;" src="../../pic/春日野穹.png"></image>
          </view>
        </view>
      </block>

      <!-- 占位 -->
      <view style="width:100%;height:18vw;"></view>
    </scroll-view>

    <!-- 输入框 -->
    <view class="inputRoom" style="bottom:{{inputBottom}}">
      <image style="width:7vw;margin-left:3.2vw;" src="../../pic/文件夹.png" mode="widthFix"></image>
      <input v-model="inputVal" @confirm="sendClick" adjust-position="{{true}}" confirm-type="send" @focus="focus" @blur="blur"></input>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      inputVal: '',
      msgList: [{
        speaker: 'server',
        contentType: 'text',
        content: '你好，我是人工智能助手，请问有什么可以帮你？'
      }],
      scrollHeight: '100vh',
      inputBottom: '0',
      cusHeadIcon: '/images/春日野穹.png',
      socketOpen: false,
      socketMsgQueue: [],
      windowWidth: wx.getSystemInfoSync().windowWidth,
      windowHeight: wx.getSystemInfoSync().windowHeight,
      keyHeight: 0,
      toView: ''
    };
  },
  methods: {
    initData() {
      this.inputVal = '';
      this.msgList = [{
        speaker: 'server',
        contentType: 'text',
        content: '你好，我是人工智能助手，请问有什么可以帮你？'
      }];
      this.scrollToBottom();
    },
    sendSocketMessage(msg) {
      if (this.socketOpen) {
        wx.sendSocketMessage({
          data: msg
        });
      } else {
        this.socketMsgQueue.push(msg);
      }
    },
    initWebSocket() {
      console.log('初始化了嘛？');
      wx.connectSocket({
        url: this.$globalData.chat_url
      });

      wx.onSocketOpen(() => {
        this.socketOpen = true;
        wx.showToast({
          icon: 'none',
          title: '连接成功',
          duration: 500
        });
        this.socketMsgQueue.forEach(msg => this.sendSocketMessage(msg));
        this.socketMsgQueue = [];
      });

      wx.onSocketMessage((result) => {
        const lastMsgIndex = this.msgList.length - 1;
        if (lastMsgIndex >= 0 && this.msgList[lastMsgIndex].speaker === 'server') {
          this.$set(this.msgList[lastMsgIndex], 'content', result.data);
        } else {
          this.msgList.push({
            speaker: 'server',
            contentType: 'text',
            content: result.data
          });
        }
        this.scrollToBottom();
      });

      wx.onSocketError(() => {
        wx.showToast({
          icon: 'none',
          title: '连接错误',
          duration: 1500
        });
      });
    },
    focus(e) {
      // 无需手动调整高度
    },
    blur() {
      this.inputBottom = '0';
      this.scrollHeight = '100vh';
      this.scrollToBottom();
    },
    sendClick(e) {
      const value = e.detail?.value || this.inputVal;
      if (!value.trim()) return;
      this.sendSocketMessage(value);
      this.msgList.push({
        speaker: 'customer',
        contentType: 'text',
        content: value
      });
      this.msgList.push({
        speaker: 'server',
        contentType: 'text',
        content: '思考中...'
      });
      this.inputVal = '';
      this.scrollToBottom();
    },
    scrollToBottom() {
      // 使用 setTimeout 确保 DOM 更新完成
      setTimeout(() => {
        const newToView = `msg-${this.msgList.length - 1}`;
        this.toView = newToView;
        console.log(`尝试滚动到 ${newToView}`);
        
        // 检查滚动是否成功
        setTimeout(() => {
          const query = wx.createSelectorQuery();
          query.select('#scrollView').scrollOffset();
          query.exec((res) => {
            if (res && res[0]) {
              console.log('当前滚动位置:', res[0].scrollTop);
            } else {
              console.log('未能获取滚动位置');
            }
          });
        }, 200);
      }, 100);
    }
  },
  mounted() {
    this.initData();
    this.initWebSocket();
    wx.onKeyboardHeightChange(res => {
      this.keyHeight = res.height;
      this.inputBottom = `${this.keyHeight}px`;
      this.scrollHeight = `${this.windowHeight - this.keyHeight}px`;
      this.scrollToBottom();
    });
  },
  beforeDestroy() {
    wx.closeSocket();
  }
};
</script>

<style>
  .inputRoom {
    width: 100vw;
    height: 16vw;
    border-top: 1px solid #cdcdcd;
    background-color: #f1f1f1;
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    z-index: 20;
  }

  .leftMsg {
    font-size: 35rpx;
    color: #444;
    line-height: 7vw;
    padding: 2vw 2.5vw;
    background-color: #fff;
    margin-left: -1.6vw;
    border-radius: 10rpx;
    z-index: 10;
  }

  .rightMsg {
    font-size: 35rpx;
    color: #444;
    line-height: 7vw;
    padding: 2vw 2.5vw;
    background-color: #96EB6A;
    margin-right: -1.6vw;
    border-radius: 10rpx;
    z-index: 10;
  }

  input {
    width: 76vw;
    height: 9.33vw;
    background-color: #fff;
    border-radius: 40rpx;
    margin-left: 2vw;
    padding: 0 3vw;
    font-size: 28rpx;
    color: #444;
  }
</style>